#ifndef _CCStreamDecoder_H_
#define _CCStreamDecoder_H_

#include "ICC_Decoder.h"
#include "CCSocketHandler.h"
#include "wspack.h"

class CCStreamDecoder : public ICC_Decoder
{
public:
	CCStreamDecoder(){};
	virtual ~CCStreamDecoder(){};

	virtual int ParsePacket(char *data, int len, CCSocketHandler *handle, CWspack *wspack)
	{
		if (DATA_PROTOCOL_UNKNOWN == handle->getDataProtocol())
		{
			if (len < 6)
			    return 0;
			if (CheckHead(data, len))
				handle->setDataProtocol(DATA_PROTOCOL_TCP);
			else if(wsCheck(data, len))
			    handle->setDataProtocol(DATA_PROTOCOL_WEBSOCKET);  
		}
		if (DATA_PROTOCOL_TCP == handle->getDataProtocol())
		{
			if ((len < 6) || (len < this->GetHeadLen(data, len)))
				return 0;

			if (!this->CheckHead(data, len))
				return -1;

			int pkglen = this->GetPacketLen(data, len);
			if (pkglen < 0)
			{
				return -1;
			}

			if (len < pkglen)
			{
				return 0;
			}
			return pkglen;
		}
		else if(DATA_PROTOCOL_WEBSOCKET == handle->getDataProtocol())
		{
			if(handle->isWshandshake())
			{
				return wspack->recv_dataframe(data, len);
			}
			else
			{
				return wspack->recv_handshake(data, len);
			}
		}

		return -1;
	}

protected:
	virtual int GetHeadLen(const char *data, int len) = 0;
	virtual bool CheckHead(const char *data, int len) = 0;
	virtual int GetPacketLen(const char *data, int len) = 0;
private:
    bool wsCheck(const char *data, int len)
	{
		if('G'== data[0] && 'E'== data[1] && 'T'== data[2])
		    return true;
		
		return false;
	}
};

#endif
